package com.jll.imageandphotoaar;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends UnityPlayerActivity {
    private final int REQUEST_Gallay = 200;
    private final int REQUEST_Camera = 300;

    private String imgPath ="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void OnOpenGallary() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_Gallay);
    }

    private void OnOpenCamera() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_DCIM);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        imgPath = image.getAbsolutePath();

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null)
        {
            Uri photoURI = FileProvider.getUriForFile(this,UnityPlayer.currentActivity.getPackageName() + ".fileprovider",image);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
            startActivityForResult(intent,REQUEST_Camera);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK)
        {
            if(requestCode == REQUEST_Gallay)
            {
                Uri selectImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = this.getContentResolver().query(selectImage,filePathColumn,null,null,null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imgPath = cursor.getString(columnIndex);
                cursor.close();

                UnityPlayer.UnitySendMessage("AndroidResponse","ChoosePhotoResponse",imgPath);
            }

            if(resultCode == RESULT_OK)
            {
                if(requestCode == REQUEST_Camera)
                {
                    UnityPlayer.UnitySendMessage("AndroidResponse","ImageCaptureResponse",imgPath);
                }
            }
        }
    }
}
